#人脸识别
import cv2
import os


def a():
    # 加载识别器
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.read('trainer/trainer3.yml')
    # 加载分类器
    cascade_path = "haarcascade_frontalface_alt2.xml"
    #cascade_path = "haarcascade_frontalface_default.xml"
    face_cascade = cv2.CascadeClassifier(cascade_path)
    cam = cv2.VideoCapture(0)
    minW = 0.1 * cam.get(3)
    minH = 0.1 * cam.get(4)
    font = cv2.FONT_HERSHEY_SIMPLEX # 定义字体
    names = []
    #agelist = [21, 21, 21, 21, 21, 21, 22]
    path = './data/jm/'
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    result = []
    for imagePath in imagePaths:
        id = int(os.path.split(imagePath)[1].split('.')[0])
        names.append(id)
    while True:
        ret, img = cam.read()
        # 左右翻转（否则向左右移动的时候，对象右左移动，反着移）
        img = cv2.flip(img, 1)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(
            gray,
            scaleFactor=1.3,
            minNeighbors=3,
            minSize=(int(minW), int(minH))
        )
        for (x, y, w, h) in faces:
            cv2.rectangle(img, (x, y), (x + w, y + h), (225, 0, 0), 2)
            img_id, confidence = recognizer.predict(gray[y:y + h, x:x + w])
            if img_id in result:
                print("已识别")
            else:
                print(img_id, confidence)
                result.append(img_id)
            #if confidence < 50:
            if confidence < 60: #调整该参数以保证正确性，越大条件约宽松
                confidence = "{0}%".format(round(100 - confidence))
            else:
                img_id = "Unknown"
                confidence = "{0}%".format(round(100 - confidence))
            if img_id != "Unknown":
                print('识别成功！！')
            else:
                print('识别失败！！')
            cv2.putText(img, str(img_id), (x, y + h), font, 0.55, (0, 255, 0), 1)
            cv2.putText(img, "18", (x, y + 500), font, 1, (0, 255, 0), 1)
            cv2.putText(img, "18", (x, y + h + 150), font, 1, (0, 255, 0), 1)
            cv2.putText(img, str(confidence), (x + 5, y - 5), font, 1, (0, 255, 0), 1)
        cv2.imshow('face', img)
        if cv2.waitKey(5) & 0xFF == 27:
            break

    cam.release()
    cv2.destroyAllWindows()
    for i in result:
        int(i)
        print(i)

a()




